package com.aharttogo.rpc.transport;

import com.ahearttogo.rpc.proto.Peer;
import org.apache.commons.io.IOUtils;
import org.eclipse.jetty.server.HttpConnection;
import sun.nio.ch.IOUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author xiejialin
 * @date 2020/2/17 3:08 PM
 */
public class HttpTransportClient implements TransportClient {

    private String url;

    @Override
    public void connect(Peer peer) {
        this.url = "http://" + peer.getHost() + ":" + peer.getPort();

    }

    @Override
    public InputStream write(InputStream data)  {
        try {

            //创建连接
            HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.connect();

            //传数据
            IOUtils.copy(data,httpURLConnection.getOutputStream());
            int resultCode = httpURLConnection.getResponseCode();
            if(resultCode == HttpURLConnection.HTTP_OK){
                return httpURLConnection.getInputStream();
            } else{
                return httpURLConnection.getErrorStream();
            }

        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    @Override
    public void close() {

    }
}
